package com.stu.shiro;

import com.stu.config.RedisUtils;
import com.stu.shiro.bean.SysUser;
import com.stu.utils.JWTUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;

/**
 * @author MI
 * @ClassName ShiroController.java
 * @createTime 2021年08月25日 16:31:00
 */
@RestController
@RequestMapping("/jwt")
public class ShiroController {

    /**
     * 公共方法
     *
     * @return
     */
    @GetMapping("comm")
    public LocalDateTime date() {
        return LocalDateTime.now();
    }

    @GetMapping("comms")
    public LocalDateTime dates() {
        return LocalDateTime.now();
    }

    @GetMapping("no")
    public LocalDateTime dateview() {
        return LocalDateTime.now();
    }

    @RequiresRoles("admin")
    @GetMapping("admin")
    public LocalDateTime dateadmin() {
        // 获取当前登录用户
        SysUser user = (SysUser) SecurityUtils.getSubject().getPrincipal();
        System.out.println(user);
        return LocalDateTime.now();
    }

    @RequiresPermissions("view")
    @GetMapping("view")
    public LocalDateTime dateNeedPre() {
        return LocalDateTime.now();
    }

    @Resource
    private RedisUtils redisUtil;

    @PostMapping("/doLogin")
    public String login(String username, String password, Integer userId, HttpServletResponse response) {
        // 拿到token之后加密
        String sign = JWTUtil.sign(username, password, userId);
        redisUtil.set(ShiroRealm.Constant.RM_TOKEN_CACHE + username, sign);
        Cookie cookie = new Cookie("token", sign);
        cookie.setMaxAge(604800);
        cookie.setHttpOnly(true);
        cookie.setPath("/");
        response.addCookie(cookie);
        return sign;
    }
}
